package com.dxy.df.config.db;

import com.alibaba.druid.pool.DruidDataSource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.sql.SQLException;

@Slf4j
@Configuration
@ConfigurationProperties(prefix ="datasource.druid")
public class DruidDataSourceConfig {


    @Autowired
    private DatasourceProperties datasourceProperties;

    @Bean
    @Primary
    public DataSource dataSource() {
        log.info("init datasource begin ...");
        DruidDataSource datasource = new DruidDataSource();
        datasource.setUrl(datasourceProperties.getDbUrl());
        datasource.setUsername(datasourceProperties.getUsername());
        datasource.setPassword(datasourceProperties.getPassword());
        datasource.setDriverClassName("com.mysql.jdbc.Driver");
        // configuration
        datasource.setInitialSize(datasourceProperties.getInitialSize());
        datasource.setMinIdle(datasourceProperties.getMinIdle());
        datasource.setMaxActive(datasourceProperties.getMaxActive());
        datasource.setMaxWait(datasourceProperties.getMaxWait());
        datasource.setTimeBetweenEvictionRunsMillis(datasourceProperties.getTimeBetweenEvictionRunsMillis());
        datasource.setMinEvictableIdleTimeMillis(datasourceProperties.getMinEvictableIdleTimeMillis());
        datasource.setTestWhileIdle(datasourceProperties.isTestWhileIdle());
        datasource.setTestOnBorrow(datasourceProperties.isTestOnBorrow());
        datasource.setTestOnReturn(datasourceProperties.isTestOnReturn());
        datasource.setPoolPreparedStatements(datasourceProperties.isPoolPreparedStatements());
        datasource.setMaxPoolPreparedStatementPerConnectionSize(
                datasourceProperties.getMaxPoolPreparedStatementPerConnectionSize());
        datasource.setQueryTimeout(datasourceProperties.getQueryTimeout());
        datasource.setTransactionQueryTimeout(datasourceProperties.getTransactionQueryTimeout());
        try {
            datasource.setFilters("stat,wall,log4j");
        } catch (SQLException e) {
            log.error("druid configuration initialization filter", e);
        }
        datasource.setConnectionProperties("druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000");
        log.info("init datasource success ...");
        return datasource;
    }
}